package capricornus.net.loader
{
	import capricornus.events.LoaderEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	[Event(name="loadComplete", type="capricornus.events.LoaderEvent")]
	[Event(name="loadProgress", type="capricornus.events.LoaderEvent")]
	[Event(name="loadProgressProportion", type="capricornus.events.LoaderEvent")]
	public class SingleUrlLoader extends EventDispatcher
	{
		private var _url:String;
		
		private var _urlLoader:URLLoader;
		
		public function SingleUrlLoader( dataFormat:String=URLLoaderDataFormat.BINARY )
		{
			super(null);
			init( dataFormat );
		}
		
		private function init( dataFormat:String ):void
		{
			_urlLoader = new URLLoader();
			_urlLoader.addEventListener( Event.COMPLETE, onLoaded, false, 0, true );
			_urlLoader.addEventListener( IOErrorEvent.IO_ERROR, onError, false, 0, true );
			_urlLoader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onError, false, 0, true );
			_urlLoader.addEventListener( ProgressEvent.PROGRESS, onProgress, false, 0, true );
			
			_urlLoader.dataFormat = dataFormat;
		}
		
		public function destroy():void
		{
			close();
			
			_urlLoader.removeEventListener( Event.COMPLETE, onLoaded );
			_urlLoader.removeEventListener( IOErrorEvent.IO_ERROR, onError );
			_urlLoader.removeEventListener( SecurityErrorEvent.SECURITY_ERROR, onError );
			_urlLoader.addEventListener( ProgressEvent.PROGRESS, onProgress );
		}
		
		public function close():void
		{
			try
			{
				_urlLoader.close();
			}
			catch( e:Error )
			{
				
			}
		}
		
		/**
		 *  
		 * @return 经过编码过的url 
		 * 
		 */		
		public function get url():String
		{
			return _url;
		}
		
		public function load( url:String ):void
		{
			_url = encodeURI(url);
			_urlLoader.load( new URLRequest( _url ) );
		}
		
		private function onLoaded( e:Event ):void
		{
			dispatchEvent( new LoaderEvent( LoaderEvent.LOAD_COMPLETE, _urlLoader.data ) );
		}
		
		private function onError( e:Event ):void
		{
			dispatchEvent( new LoaderEvent( LoaderEvent.LOAD_COMPLETE, null ) );
		}
		
		private function onProgress( e:ProgressEvent ):void
		{
			dispatchEvent( new LoaderEvent( LoaderEvent.LOAD_PROGRESS, e.bytesLoaded ) );
			dispatchEvent( new LoaderEvent( LoaderEvent.LOAD_PROGRESS_PROPORTION, e.bytesLoaded/e.bytesTotal ) );
		}
	}
}









